/**
 * Created by wangzhuoya on 2017/7/7.
 */
/**折线图
 * exportForm 定义导出的csv表头和对应的列
 * 
 * **/
function lineChartModal(data,id,x,y,z,xTtile,yTtile,chartHeight,defs,exportForm){
    $("#"+id).html("");
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight
    });
    chart.source(data,defs);
    chart.legend({
        position: 'top', // 设置图例的显示位置
        itemWrap: true,
        dy: -10 // 整个图例的垂直偏移距离
    });
    if(isEmpty(xTtile)){
        chart.axis(x, {
            title: null
        });
    }
    if(isEmpty(yTtile)){
        chart.axis(y, {
            title: null
        });
    }
    chart.line().position(x+'*'+y).color(z);
    chart.render();
    download(data,id,chart);
    downloadCsv(data,id,chart,defs,"line",exportForm);
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}


/** 柱状图 
 *  exportForm 定义导出的csv表头和对应的列
 * **/
function histogramModal(data,id,x,y,xTtile,yTtile,chartHeight,defs){
    $("#"+id).html("");
    // Step 1: 创建 Chart 对象
    var chart = new G2.Chart({
        id: id, // 指定图表容器 ID
        forceFit: true,
        height : chartHeight // 指定图表高度
    });
    // Step 2: 载入数据源,定义列信息
    chart.source(data,defs);
    if(isEmpty(xTtile)){
        chart.axis(x, {
            title: null
        });
    }
    if(isEmpty(yTtile)){
        chart.axis(y, {
            title: null
        });
    }
    chart.tooltip(true, {
  	  title: null // 默认标题不显示
  	});
    chart.legend({
        position: 'top', // 设置图例的显示位置
        itemWrap: true,
        dy: -10 // 整个图例的垂直偏移距离
    });
    // Step 3：创建图形语法，绘制柱状图，由 x 和 y 两个属性决定图形位置，x 映射至 x 轴，y 映射至 y 轴
    chart.interval().position(x+'*'+y).color(x).label(y).size(25);
    // Step 4: 渲染图表
    chart.render();
    download(data,id,chart);
    downloadCsv(data,id,chart,defs,"bar");
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}

/** 饼图 
 * exportForm 定义导出的csv表头和对应的列
 ***/
function pieChartModal(data, id, x, y, chartHeight,defs,exportForm) {
    $("#" + id).html("");
    var Stat = G2.Stat;
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight
    });
    chart.source(data);
    // 重要：绘制饼图时，必须声明 theta 坐标系
    chart.coord('theta', {
        radius: 0.8 // 设置饼图的大小
    });
    chart.legend(x, {
        position: 'bottom',
        itemWrap: true
    });
    chart.intervalStack()
        .position(Stat.summary.percent(y))
        .color(x)
        .label(x, {
            renderer: function (text, item, index) {
                var point = item.point; // 每个弧度对应的点
                var percent = point['..percent']; // ..percent 字段由 Stat.summary.percent 统计函数生成
                percent = (percent * 100).toFixed(2) + '%';
                return text + ' ' + percent;
            }
        });
    chart.render();
    download(data, id, chart);
    //导出csv
    downloadCsv(data,id,chart,defs,"pie",exportForm);
    if (data == null || data.length == 0) {
        tips(id, chartHeight);
    }
    return chart;
}

/** 横向柱状图 
 *defs:定义导出的csv表头
 *exportForm: 定义导出的表头和对应的列,优先使用这个定义
 ***/
function horizontalHistogramModal(data,id,x,y,chartHeight,defs,exportForm){
    $("#"+id).html("");
    var Frame = G2.Frame;
    var frame = new Frame(data);
    frame = Frame.sort(frame, y); // 将数据按照y进行排序，由大到小
    var chart = new G2.Chart({
        id : id,
        forceFit: true,
        height: chartHeight,
        plotCfg: {
            margin: [20, 60, 20, 120]
        }
    });
    if(data == null || data.length == 0){
        tips(id,chartHeight);
        return;
    }
    chart.source(frame);
    chart.axis(x,{
        title: null
    });
    chart.tooltip(true, {
  	  title: null // 默认标题不显示
  	});
    chart.legend(false);
    chart.coord('rect').transpose();
    chart.interval().position(x+'*'+y).color(x).label(y).size(15);
    chart.render();
    download(data,id,chart);
    //下载csv
    downloadCsv(data,id,chart,defs,"horizBar",exportForm);
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}


/** 漏斗图 **/
function funnelModal(data,id,x,y,type,chartHeight){
    $("#"+id).html("");
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight
    });
    if(data == null || data.length == 0){
        tips(id,chartHeight);
        return chart;
    }
    chart.source(data);
    chart.legend(false);
    chart.coord('rect').transpose().scale(1,-1);
    chart.axis(false);
    var jsonData = data.sort(function(a, b){return (a.value < b.value) ? 1 : -1});
    chart.intervalSymmetric().position(x+'*'+y).color(x).shape('pyramid').label(x, {
        offset:5,
        renderer: function(text, item, index) {
            var point = item.point; // 每个弧度对应的点
            $.each(jsonData,function(idx){
                if(jsonData[idx].value == point.value && jsonData[idx].name == text){
                    funnelIndex = idx;//idx为数组下标
                }
            });
            if(point.value == 0 || funnelIndex == 0){
                return text + '\n'+type+"总量"+point.value;
            }else{
                var ratio = point.value / jsonData[funnelIndex-1].value * 100;
                return text + '\n'+type+"总量"+point.value+"\n占比" + ratio.toFixed(2) +"%";
            }
        }
    }).animate({
        appear:{
            animation:'zoomIn'
        },
        enter:{
            animation:'fadeIn',
            easing:'easeInQuart'
        }
    });
    chart.render();
    chart.on('tooltipchange', function(ev) {
        var items = ev.items; // tooltip显示的项
        var origin = items[0]; // 将一条数据改成多条数据
        var proportion;
        $.each(yDataAmonut1,function(idx){
            if(yDataAmonut1[idx].value == origin.value && yDataAmonut1[idx].name == origin.name){
                funnelIndex = idx;//idx为数组下标
            }
        });
        if(origin.value != 0 && funnelIndex != 0){
            var ratio = origin.value / yDataAmonut1[funnelIndex-1].value * 100;
            proportion = ratio.toFixed(2) +"%";
        }
        items.splice(0); // 清空
        items.push({
            name: type+'总量',
            title: origin.title,
            marker: true,
            color: origin.color,
            value: origin.value
        });
        if(proportion != undefined){
            items.push({
                name: '占比',
                marker: true,
                title: origin.title,
                color: origin.color,
                value:proportion
            });
        }
    });
    download(data,id,chart);
    return chart;
}

/**
 *  分组柱状图
 *  data 数据
 *  catetory 柱状图标题
 *  titlex x轴标题
 *  titley y轴标题
 *  id 图标ID
 *  height 图表高度
 *  cutline 图例标题
 *  exportForm 定义导出的表头
 **/
function makeGroupBarGraphModal(data, category, titlex, titley, id, height, cutline, exportForm) {
    if(null == data || data == "" || data.length <= 0) {
        tips(id, height);
        return null;
    } else {
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            var datas = item.data;
            for (var j = 0; j < datas.length; j++) {
                item[category[j]] = datas[j];
            }
            data[i] = item;
        }
        var Stat = G2.Stat;
        var Frame = G2.Frame;
        var frame = new Frame(data);
        frame = Frame.combinColumns(frame, category, titley, titlex, 'name');
        var chart = new G2.Chart({
            id: id,
            forceFit: true,
            height: height,
            plotCfg: {
                margin: [20, 90, 80, 90]
            }
        });
        chart.source(frame);
        chart.col('name', {alias: cutline});
        chart.intervalDodge().position(titlex + "*" + titley).color('name');
        chart.render();
        download(data, id, chart);
        //导出csv
        downloadCsv({"exdata":data,"category":category}, id, chart,"","groupBar",exportForm);
        return chart;
    }
}

function makeShanModal(data,id,chartHeight){
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight,
        plotCfg: {
            margin: [45, 20, 90]
        }
    });
    chart.source(data, {
        'amount': {
            min: 0
        }
    });
    chart.coord('polar', {
        startAngle: Math.PI, // 起始角度
        endAngle: Math.PI * (3 / 2) // 结束角度
    });
    chart.axis('amount', {
        labels: null
    });
    chart.axis('time', {
        gridAlign: 'middle',
        labels: {
            label: {
                textAlign: 'right' // 设置坐标轴 label 的文本对齐方向
            }
        }
    });
    chart.legend('time', {
        position: 'bottom',
        itemWrap: true // 图例需要换行
    });
    chart.interval().position('time*amount')
        .color('time','rgb(240, 208, 109)-rgb(237, 109, 92)')
        .label('amount',{offset: -15,label: {textAlign: 'center', fill: '#000'}})
        .style({
            lineWidth: 1,
            stroke: '#fff'
        });
    chart.render();
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}

function makePerModal(data,id,chartHeight){
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight,
        plotCfg: {
            margin: [35, 230, 35, 20]
        }
    });
    chart.source(data, {
        'cost': {
            min: 0
        }
    });
    chart.coord('polar');
    chart.axis('cost', {
        labels: null
    });
    chart.axis('category', {
        gridAlign: 'middle',
        labelOffset: 10,
        labels: {
            label: {
                textAlign: 'center' // 设置坐标轴 label 的文本对齐方向
            }
        }
    });
    chart.legend('category', {
        itemWrap: true // 图例换行，将该参数设置为 true, 默认为 false，不换行。
    });
    chart.interval().position('category*cost')
        .color('category','rgb(229, 204, 95)-rgb(125, 204, 95)')
        .label('cost',{offset: -15,label: {textAlign: 'center', fontWeight: 'bold'}})
        .style({
            lineWidth: 1,
            stroke: '#fff'
        });
    chart.render();
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}

/*词云*/
function makeCloudModal(data,id){
    $("#"+id).html("");
    var width = $("#"+id).width();
    var height = $("#"+id).height();
    if(data == null || data.length < 8){
        tips(id,height);
    }else{
        var Util = G2.Util;
        var Shape = G2.Shape;
        function getTextAttrs(cfg) {
            var textAttrs = Util.mix(true, {}, {
                fillOpacity: cfg.opacity,
                fontSize: cfg.size,
                rotate: cfg.origin._origin.rotate,
                text: cfg.origin._origin.text,
                textAlign: 'center',
                fill: cfg.color,
                textBaseline:'Alphabetic'
            }, cfg.style);
            return textAttrs;
        }
        // 给point注册一个词云的shape
        Shape.registShape('point', 'cloud', {
            drawShape: function(cfg, container) {
                cfg.points = this.parsePoints(cfg.points);
                var attrs = getTextAttrs(cfg);
                // 给容器添加text类型的shape
                // 坐标仍然是原来的坐标
                // 文字样式为通过getTextAttrs方法获取的样式
                var shape = container.addShape('text', {
                    attrs: Util.mix(attrs, {
                        x: cfg.points[0].x,
                        y: cfg.points[0].y
                    })
                });
                return shape;
            }
        });

        data.sort(function(a,b){
            return b.amount-a.amount;
        });
        // 获取数据的最大值和最小值
        var max = data[0].amount;
        var min = data[data.length-1].amount;
        // 构造一个词云布局对象
        var layout = new Cloud({
            // 传入数据源
            words: data,
            // 设定宽高（默认为500*500）
            width: width,
            height: height,
            // 设定文字大小配置函数(默认为12-40px的随机大小)
            size: function(words){
                // 将pv映射到canvas可绘制的size范围14-100(canvas默认最小文字为12px)
                return ((words.amount - min)/(max - min)) * (100 - 14) + 14;
            },
            // 设定文字内容
            text: function(words){
                var text = words.viewpoint;
                return text;
            }
        });
        // 执行词云布局函数，并在回调函数中调用G2对结果进行绘制
        layout.exec(function(texts){
            var chart = new G2.Chart({
                id : id,
                // canvas的宽高需要和布局宽高一致
                width: width,
                height: height,
                plotCfg : {
                    margin : 0
                }
            });
            chart.legend(false);
            chart.source(texts);
            chart.axis(false);
            chart.tooltip({
                title:false
            });
            // 将词云坐标系调整为G2的坐标系
            chart.coord().reflect();
            // 绘制点图，在x*y的坐标点绘制自定义的词云shape，颜色根据text字段进行映射，大小根据size字段的真实值进行映射，文字样式配置为词云布局返回的样式，tooltip显示site*pv两个字段的内容
            chart.point().position('x*y').color('text').size('size',function(size){
                return size;
            }).shape('cloud').style({
                fontStyle: texts[0].style,
                fontFamily: texts[0].font,
                fontWeight: texts[0].weight
            }).tooltip('viewpoint*amount');
            chart.render();
        });
    }
}

/**折线图
 * @param isLegend 是否显示图例,默认显示(true)
 * **/
function lineChartNoSpider(data, id, x, y, z, xTtile, yTtile, chartHeight, defs, isLegend,exportForm) {
    $("#" + id).html("");
    var chart = new G2.Chart({
        id: id,
        forceFit: true,
        height: chartHeight,
        plotCfg: {
            margin: [20, 40, 65, 50] // 上，右，下，左
        }
    });
    chart.source(data,defs);
    if (null != isLegend && isLegend != "") {
        chart.legend({
            position: 'top', // 设置图例的显示位置
            itemWrap: true,
            dy: -20 // 整个图例的垂直偏移距离
        });
    } else {
        chart.legend(false);
    }
    chart.line().position(x + '*' + y).color(z).style({
        lineWidth: 2
    });
    if(isEmpty(xTtile)){
        chart.axis(x, {
            title: null
        });
    }
    if(isEmpty(yTtile)){
        chart.axis(y, {
            title: null
        });
    }
    chart.render();
    download(data,id,chart);
    //导出csv
    downloadCsv(data, id, chart,"","lineNoSpider",exportForm);
    if(data == null || data.length == 0){
        tips(id,chartHeight);
    }
    return chart;
}

function isEmpty(m) {
    if (null == m || m.trim() == "") {
        return true;
    } else {
        return false;
    }
}

function download(data,id,chart){
    if(data!="" && data!=null){
        if($("#download_"+id).length <= 0){
            var html = "<label id='download_"+id+"' style='float: right;font-size:20px!important;padding-right: 5px;color: #669fc7;'>"+
                "<i class='ace-icon fa fa-cloud-download'></i>"+
                "</label>";
            $("#"+id).parent().parent().children().children("h4").append(html);
        }
        $("#download_"+id).unbind("click");
        $("#download_"+id).on("click",function(){
            chart.downloadImage();
        });
    }else{
        if($("#download_"+id).length > 0){
            $("#download_"+id).remove();
        }
    }
}
/**
 * 
 * @param data
 * @param id
 * @param chart
 * @param defs
 * @param chartType
 * @param exportForm 传入导出表头exportForm.headers=[]和对应列名exportForm.cols=[]
 * @return
 */
function downloadCsv(data,id,chart,defs,chartType,exportForm){
    if(data!="" && data!=null){
        if($("#download_"+id+"_csv").length <= 0){
            var html = "<span class='label label-lg label-purple arrowed' style='float:right;margin-top:5px;margin-right:10px;padding: 5px;' id='download_"+id+"_csv' >导出</span>";
            $("#"+id).parent().parent().children().children("h4").append(html);
        }
        $("#download_"+id+"_csv").unbind("click");
        $("#download_"+id+"_csv").on("click",function(){
        	var filename=$(this).parent().text().trim();
        	if(filename.indexOf("\n")!=-1){
        		filename = filename.substring(0,filename.indexOf("\n"));
        	}
        	//如果传入了导出的csv表头及对应列名
        	if(typeof exportForm != 'undefined' && exportForm!=""){
        		var headers  = exportForm.headers;
        		var cols     = exportForm.cols;
        		if(chartType=="groupBar"){//分组柱状图

        			var exportData=[];
        			for(var i=0;i<data.exdata[0].data.length;i++){
                        var tempObj=new Object();
                        tempObj[cols[0]]=data.category[i];
        			   for(var j=0;j<data.exdata.length;j++)
                            tempObj[data.exdata[j].name]=data.exdata[j].data[i];
                            exportData.push(tempObj);
                    }

        			// for(var i=0;i<data.length;i++){
        			// 	for(var key in data[i]){
        			// 		if(key!="name" && key!="data"){
        			// 			var tempObj=new Object();
        			// 			tempObj["name"]=data[i].name
        			// 			tempObj['category']=key;
        			// 			tempObj['amount']=data[i][key];
        			// 			exportData.push(tempObj);
        			// 		}
        			// 	}
        			// }
        			// var compare = function(a,b){
        			// 	var pa=3;
        			// 	var pb=3;
        			// 	if(a.name=="好评量"){
        			// 		pa=1;
        			// 	}else if(a.name=="中评量"){
        			// 		pa=2;
        			// 	}
        			// 	if(b.name=="好评量"){
        			// 		pb=1;
        			// 	}else if(b.name=="中评量"){
        			// 		pb=2;
        			// 	}
        			// 	if(a.category!=b.category){
        			// 		return a.category>b.category?1:-1;
        			// 	}else{
        			// 		return pa>pb?1:-1;
        			// 	}
        			// }
        			exportCsv(filename,exportData,headers,cols,"");
        		}else{
        			if(exportForm.hasOwnProperty("compareMethod")){
        				exportCsv(filename,data,headers,cols,"",exportForm.compareMethod);
        			}else{
        				if(exportForm.hasOwnProperty("sortCols")){
    	        			exportCsv(filename,data,headers,cols,exportForm.sortCols);
    	        		}else{
    	        			exportCsv(filename,data,headers,cols);
    	        		}
        			}
	        		
        		}
        	}else{//如果未传入导出的csv表头及对应列名，默认按如下方式取
        		if(chartType=="pie"){//饼图
            		var headers = ['类别','占比'];
            		var cols=['name','value'];
            		exportCsv(filename,data,headers,cols);
            		return;
            	}
        		//通过defs获取表头
        		var category="category";
            	if(defs.hasOwnProperty("categoryName")){
            		category="categoryName";
            	}
            	if(defs.hasOwnProperty("platform")){
        			category="platform";
        		}
        		if(chartType=="line"){//线图
        			var headers=[];
                	headers.push(defs[category].alias);
            		headers.push(defs.time.type);
            		headers.push(defs.amount.alias);
            		var cols=[category,"time","amount"];
            		var sortCols=[category,"time"];
                    exportCsv(filename,data,headers,cols,sortCols);
            	}else{//柱状图
            		var headers=[];
                	headers.push(defs[category].alias);
                	headers.push(defs.amount.alias);
                	var cols=[category,"amount"];
            		exportCsv(filename,data,headers,cols);
            	}
        	}
        	
        });
    }else{
        if($("#download_"+id+"_csv").length > 0){
            $("#download_"+id+"_csv").remove();
        }
    }
}

function tips(id,chartHeight){
   var str =  "<div style='top: 50%;left: 50%;position: absolute;transform: translate(-50%, -50%);'><img style='width:18.89px;height:18.89px' src='../images/sad-big.png' /><span style='color:#333333;padding-left: 2px'>暂无数据</span></div>";
    $("#"+id).html("");
    $("#"+id).css("height",chartHeight);
    $("#"+id).append(str);
}